# 复制例子场景编辑策略
import time
import Comment
import sys
import random
import os


class exampleStage:
    def __init__(self, queue, final=0):
        self.remote = 1
        self.final = final
        self.swipePath = r'G:\python\exampleStage\2'
        #滑动到底比较图存放地址
        self.swipeFile = 'swipe'
        self.className = 'exampleStage'
        # 未识别场景存放路径
        self.unknownpath = r'G:\python\exampleStage\unknown'
        # 截图存放地址
        self.shotpath = 'G:\python\img';
        self.shotpFullPath = 'G:\\python\\img\\tmp.jpg';
        # 日志名
        self.log = r'exampleStage';
        # 未命中响应场景 休眠时间
        self.sleepTime = 5
        # 超出试错次数终止程序
        self.times = 2
        self.queue = queue
        # 固定场景字典
        self.stage = {
            # 手机主屏场景
            'home': {
                # 场景图地址
                'stage': r'G:\python\exampleStage\1\home.png',
                # 响应场景
                'activeStage': {
                    # 动作1
                    'openApp': {
                        # 未命中：执行方法
                        'miss': 'swipeScreen',
                        # 命中:匹配图
                        'hit': r'G:\python\alipay\1\open.png',
                    },
                },
            },
        }

    # 自定义解锁L形
    def myLock(self, res):
        os.system(
            'adb shell sendevent /dev/input/event2 0003 0057 00008780 &adb shell sendevent /dev/input/event2 0001 0330 00000001 &adb shell sendevent /dev/input/event2 0003 0053 00000567 &adb shell sendevent /dev/input/event2 0003 0054 00000739 &adb shell sendevent /dev/input/event2 0003 0049 00000004 &adb shell sendevent /dev/input/event2 0000 0000 00000000 &adb shell sendevent /dev/input/event2 0003 0053 00000553 &adb shell sendevent /dev/input/event2 0003 0054 00000798 &adb shell sendevent /dev/input/event2 0003 0048 00000006 &adb shell sendevent /dev/input/event2 0000 0000 00000000 &adb shell sendevent /dev/input/event2 0003 0053 00000502 &adb shell sendevent /dev/input/event2 0003 0054 00001360 &adb shell sendevent /dev/input/event2 0003 0049 00000004 &adb shell sendevent /dev/input/event2 0000 0000 00000000 &adb shell sendevent /dev/input/event2 0003 0053 00000530 &adb shell sendevent /dev/input/event2 0003 0054 00001395 &adb shell sendevent /dev/input/event2 0003 0048 00000005 &adb shell sendevent /dev/input/event2 0003 0049 00000003 &adb shell sendevent /dev/input/event2 0000 0000 00000000 &adb shell sendevent /dev/input/event2 0003 0053 00000926 &adb shell sendevent /dev/input/event2 0003 0054 00001404 &adb shell sendevent /dev/input/event2 0003 0048 00000005 &adb shell sendevent /dev/input/event2 0000 0000 00000000 &adb shell sendevent /dev/input/event2 0003 0057 4294967295 &adb shell sendevent /dev/input/event2 0000 0000 00000000')
        self.showMsg('执行解锁')
        self.actionSleep(5)

    def setFinal(self, value):
        self.final = value

    # 未命中执行上下滑动搜寻场景目标（ 识别特殊任务场景）
    def swipe(self):
        # 识别特殊任务场景
        closePic = r'G:\python\alipay\2\close.png'
        # 写入队列场景
        self.showMsg('主线程：匹配是否存在任务')
        self.showStage(closePic)
        res = Comment.matchImg("%s\\tmp.jpg" % (self.shotpath), closePic, 0.9)
        self.showMsg(res)
        if (res):
            self.showMsg('主线程：发现任务,关闭任务')
            self.click(res)
        else:
            self.showMsg('主线程：不存在任务弹框,判断是否滑动到底')
            if os.path.exists("%s\\%s.jpg" % (self.swipePath, self.swipeFile)):
                res = Comment.matchImg("%s\\tmp.jpg" % (self.shotpath), "%s\\%s.jpg" % (self.swipePath, self.swipeFile),
                                       0.9)
                if res:
                    self.showMsg(res)
                    self.showMsg('发现已滚动到底部')
                    self.showMsg('final为%s' % (self.final))
                    # 判断方向
                    if self.final == 1:
                        # 下滑动
                        self.swipe_down()
                        self.final = 0
                        self.showMsg('final置为%s' % (self.final))
                    else:
                        self.swipe_up()
                        self.final = 1
                        self.showMsg('!!!!!!!!!final置为%s' % (self.final))
                else:
                    self.showMsg('final为%s' % (self.final))
                    if self.final == 1:
                        self.swipe_up()
                    else:
                        self.swipe_down()
            self.showStage("%s\\%s.jpg" % (self.swipePath, self.swipeFile))
            Comment.screenShot("%s\\%s.jpg" % (self.swipePath, self.swipeFile))
            self.showMsg('留存本次滑动截图,休眠5s')
            # time.sleep(5)
            return self.final

    def swipe_down(self):
        self.showMsg('执行向下滑动操作')
        Comment.swipe_screen(718, 1000, 818, 418, 150)

    def swipe_up(self):
        self.showMsg('执行向上滑动操作')
        Comment.swipe_screen(818, 418, 718, 1000, 150)

    # 响应场景事件
    # 打开app
    def openApp(self, res):
        x, y = res['result']
        #识别名字 向上偏移
        k = (x, y - 90)
        self.click(k)
        self.showMsg('正在打开APP')
        self.actionSleep(10)
    #针对场景不同操作
    def getFriend(self, res):
        # 增加坐标偏移
        x, y = res['result']
        k = (x, y - 90)
        self.click(k)
        self.showMsg('正在收取朋友能量球')
        self.actionSleep(2)

    # 针对场景不同操作
    def getHand(self, res):
        self.click(res)
        self.showMsg('查找朋友谁有能量球')
        self.actionSleep(5)

    # 倒计时休眠
    def actionSleep(self, t):
        while t:
            self.showMsg("倒计时 %s 秒" % (t))
            time.sleep(1)
            t = t - 1

    # 点击事件
    def click(self, res):
        if 'result' in res:
            x, y = res['result']
        else:
            x, y = res
        Comment.tap_screen(x, y)
        # 画图保存
        self.drawCircle(res)

    # 画圆圈
    def drawCircle(self, res):
        Comment.click_draw(self.shotpFullPath, res)
        self.showAction(self.shotpFullPath)

    def sleep(self):
        self.showMsg('未命中响应场景，休眠10s...')
        time.sleep(10)
        Comment.tap_screen(700, 1400)

    # 打开游戏
    def gameStart(self, result):
        x, y = result['result']
        Comment.tap_screen(x, y)
        # 画图保存
        Comment.click_draw(self.shotpFullPath, result)
        self.showAction(self.shotpFullPath)
        self.showMsg('点击坐标%s%s' % (x, y))
        self.showMsg('正在打开游戏.....休眠15s')
        time.sleep(15)

    def write_log(self, message):
        Comment.log(message, self.log)

    # 滑屏寻找app
    def swipeScreen(self):
        Comment.swipe_screen(718, 1367, 335, 1367, 800)
        Comment.screenShot(self.shotpath)

    # 打开目标
    def openApp(self, result):
        x, y = result['result']
        Comment.tap_screen(x, y)
        # 画图保存
        # print(result)
        Comment.click_draw(self.shotpFullPath, result)
        self.showAction(self.shotpFullPath)
        self.showMsg('点击坐标%s%s' % (x, y))
        self.showMsg('点击坐标%s%s' % (x, y))
        self.showMsg('正在打开目标.....休眠10s')
        time.sleep(10)

    # 显示消息
    def showMsg(self, msg):
        print("%s | 行号:%s" % (msg, sys._getframe().f_back.f_lineno))
        content = Comment.formatMsg(msg)
        Comment.putQueue(self.queue, content)

    # 显示图片
    def showStage(self, path):
        print(path)
        content = Comment.formatStage(path)
        Comment.putQueue(self.queue, content)

    def showAction(self, path):
        print(path)
        content = Comment.formatAction(path)
        Comment.putQueue(self.queue, content)

    def back(self):
        Comment.back()
        self.showMsg('返回上一页.....休眠3s')
        time.sleep(3)

    def clickHome(self, res):
        Comment.home()
        self.showMsg('返回HOME.....休眠1s')
        time.sleep(1)

    # 主策略
    def Start(self, unknown=0):
        # 实例化函数
        mod = eval(self.className)(self.queue, self.final)
        self.showMsg(mod)
        # 滑动到底部 1为到 0为未到
        stageKey = 0
        # 手机截图并存放到指定目录返回目录
        result = Comment.screenShot(self.shotpath)
        if result:
            self.showMsg('截图成功')
            self.showAction(result)
            # 取出场景
            for key in self.stage:
                # 写入队列场景
                self.showStage(self.stage[key]['stage'])
                # exit()
                res = Comment.matchImg(result, self.stage[key]['stage'], 0.9)
                self.showMsg(res)
                # exit()
                self.showMsg('<<<<<<<搜寻所处场景>>>>>>>')
                # 获取匹配场景
                if res:
                    stageKey = key
                    self.showMsg("####已匹配到#### 处在场景%s" % (key))
                    time.sleep(3)
                    unknown = 1
                    # exit()
                    break;
            if stageKey == 0:
                Comment.screenShot(self.unknownpath)
                if unknown > 0:
                    self.showMsg('!!!!!!未知场景')
                    self.write_log("!!!!!未知场景: %s" % (key))
                    self.showMsg('退出')
                    exit()
                self.showMsg('~~~~~初始化到首页~~~~~')
                Comment.home()
                return self.Start()
        else:
            self.showMsg('未获取到手机截图')
            exit()
        # 调用响应场景
        self.showMsg('<<<<<<<<搜寻响应场景>>>>>>>>')
        for k in self.stage[stageKey]['activeStage']:
            # 展示场景
            self.showStage(self.stage[stageKey]['activeStage'][k]['hit'])
            while True:
                print("!!!!!!!!!final当前为%s" % (self.final))
                if unknown > 15:
                    self.back()
                    break;
                if unknown > 100:
                    Comment.screenShot(self.unknownpath)
                    self.showMsg('!!!!!!未知响应场景')
                    self.write_log("!!!!!未知响应场景: %s" % (key))
                    self.showMsg('退出')
                    exit()
                    # self.showMsg(self.stage[stageKey]['activeStage'][k])
                # exit()
                result = Comment.screenShot(self.shotpath)
                self.showAction(result)
                print('\n\n\n开始计算匹配度>>>>>>>>>>')
                # 主响应策略
                if (k == 'getFriend' and stageKey == 'friend'):
                    pass#此处为特殊方法
                else:
                    res = Comment.matchImg(result, self.stage[stageKey]['activeStage'][k]['hit'], 0.8)
                    print(res)
                if res:
                    self.showMsg("@@@@找到响应场景%s" % (k))
                    # 找到函数方法
                    fun = getattr(mod, k)
                    fun(res)
                    break
                else:
                    self.showMsg("@@@@未命中响应场景%s" % (k))
                    # 判断miss场景
                    self.showMsg("执行miss方法%s" % (self.stage[stageKey]['activeStage'][k]['miss']))
                    # time.sleep(5)
                    fun = getattr(mod, self.stage[stageKey]['activeStage'][k]['miss'])
                    # 找不到能量球朋友场景 上下滑动
                    if (self.stage[stageKey]['activeStage'][k]['miss'] == 'swipe'):
                        print("!!!!!!!!!final当前为%s" % (self.final))
                        self.final = fun()
                    elif (self.stage[stageKey]['activeStage'][k]['miss'] == 'next'):
                        self.showMsg("@@@@未找到响应场景%s,跳出寻找场景" % (k))
                        break
                    else:
                        print("miss函数当前为%s" % (self.stage[stageKey]['activeStage'][k]['miss']))
                        fun()
                    unknown = unknown + 1
                    self.showMsg("***********未命中置为%s" % (unknown))
        return self.Start(unknown)

